package com.love.marriage.datingInfo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.marriage.common.enums.DefaultAmountTypeEnum;
import com.love.marriage.common.enums.ResultEnum;
import com.love.marriage.common.enums.TransactionType;
import com.love.marriage.common.exceptions.SystemException;
import com.love.marriage.common.vo.SecurityUser;
import com.love.marriage.config.DefaultAmountConfig;
import com.love.marriage.datingInfo.entity.DatingInfo;
import com.love.marriage.datingInfo.mapper.DatingInfoMapper;
import com.love.marriage.datingInfo.service.DatingInfoService;
import com.love.marriage.datingInfo.vo.DatingInfoResVo;
import com.love.marriage.datingInfo.vo.DatingInfoVo;
import com.love.marriage.datingRegistrationInfo.mapper.DatingRegistrationInfoMapper;
import com.love.marriage.datingRegistrationInfo.vo.DatingRegistrationInfoVo;
import com.love.marriage.defaultAmountConfig.service.DefaultAmountConfigService;
import com.love.marriage.defaultAmountConfig.vo.DefaultAmountConfigVo;
import com.love.marriage.oss.service.FileInfoService;
import com.love.marriage.oss.vo.FileInfoVo;
import com.love.marriage.userActivityInfo.service.UserActivityInfoService;
import com.love.marriage.userActivityInfo.vo.UserActivityInfoVo;
import com.love.marriage.userBalanceInfo.service.UserBalanceInfoService;
import com.love.marriage.userBalanceInfo.vo.UserBalanceInfoAddVo;
import com.love.marriage.userBalanceInfo.vo.UserBalanceInfoVo;
import com.love.marriage.utils.StringUtils;
import com.love.marriage.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * description:  约会表服务实现类
 * author:       alex
 * createDate:   2024-10-15 20:28:51
 * version:      1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DatingInfoServiceImp extends ServiceImpl<DatingInfoMapper, DatingInfo> implements DatingInfoService {

    private final DatingInfoMapper datingInfoMapper;

    private final FileInfoService fileInfoService;

    private final DefaultAmountConfig defaultAmountConfig;

    private final UserBalanceInfoService userBalanceInfoService;

    private final DefaultAmountConfigService defaultAmountConfigService;

    private final UserActivityInfoService userActivityInfoService;
    private final DatingRegistrationInfoMapper datingRegistrationInfoMapper;

    @Override
    public Page<DatingInfoResVo> getPage(Long pageNum, Long pageSize, DatingInfoVo datingInfoVo) {
        SecurityUser loginUser = UserUtils.getLoginUser();
        Long curUserId = null;
        if (datingInfoVo != null && datingInfoVo.getUserId() != null) {
            curUserId = datingInfoVo.getUserId();
        } else if (loginUser != null) {
            curUserId = loginUser.getId();
        }
        Page<DatingInfoVo> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        Page<DatingInfoResVo> res = datingInfoMapper.getPage(page, datingInfoVo, curUserId);
        if (res.getRecords() != null && !res.getRecords().isEmpty()) {
            res.getRecords().forEach(datingInfoResVo -> {
                        if (datingInfoResVo.getAvatar() != null) {
                            try {
                                datingInfoResVo.setPersonAvatar(fileInfoService.queryFileInfo(datingInfoResVo.getAvatar()));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
            );
        }
        return res;
    }

    @Override
    public List<DatingInfoResVo> getList(DatingInfoVo datingInfoVo) {
        List<DatingInfoResVo> res = datingInfoMapper.getList(datingInfoVo, null);
        if (res != null && !res.isEmpty()) {
            res.forEach(datingInfoResVo -> {
                        if (datingInfoResVo.getAvatar() != null) {
                            try {
                                datingInfoResVo.setPersonAvatar(fileInfoService.queryFileInfo(datingInfoResVo.getAvatar()));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
            );
        }
        return res;
    }

    @Override
    public DatingInfoResVo queryDatingInfo(Long id, Long userId, String type) {
        SecurityUser loginUser = UserUtils.getLoginUser();
        Long curUserId = userId;
        if (curUserId == null && loginUser != null) {
            curUserId = loginUser.getId();
        }
        DatingInfoResVo datingInfoVo = datingInfoMapper.queryDatingInfo(id, curUserId);
        if (StringUtils.isNotBlank(datingInfoVo.getImageIds())) {
            List<Long> imageIds = Arrays.stream(datingInfoVo.getImageIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<FileInfoVo> fileInfoVoList = fileInfoService.getFileInfo(imageIds);
            datingInfoVo.setFileInfoVoList(fileInfoVoList);
        }
        if (datingInfoVo.getAvatar() != null) {
            try {
                datingInfoVo.setPersonAvatar(fileInfoService.queryFileInfo(datingInfoVo.getAvatar()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if (datingInfoVo.getSharePhotoId() != null) {
            try {
                FileInfoVo sharePhotoFile = fileInfoService.queryFileInfo(datingInfoVo.getSharePhotoId());
                datingInfoVo.setSharePhotoFile(sharePhotoFile);
            } catch (Exception e) {
                log.error("查询微信二维码失败，userId:{}，错误信息：{}", datingInfoVo.getUserId(), e.getMessage());
            }
        }
        // 处理微信二维码文件
        if (datingInfoVo.getUserProfileInfoVo() != null && datingInfoVo.getUserProfileInfoVo().getWechatQrCodeId() != null) {
            try {
                FileInfoVo wechatQrCodeFile = fileInfoService.queryFileInfo(datingInfoVo.getUserProfileInfoVo().getWechatQrCodeId());
                datingInfoVo.getUserProfileInfoVo().setWechatQrCodeFile(wechatQrCodeFile);
            } catch (Exception e) {
                log.error("查询用户微信二维码失败，userId:{}，错误信息：{}", datingInfoVo.getUserId(), e.getMessage());
            }
        }
        if (datingInfoVo.getPayMoney() == null) {
            DefaultAmountConfigVo defaultAmountConfigVo = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.JOIN_DATING.getCode());
            if (defaultAmountConfigVo != null) {
                datingInfoVo.setPayMoney(defaultAmountConfigVo.getAmount());
            } else {
                datingInfoVo.setPayMoney(BigDecimal.ZERO);
            }
        }
        if ("detail".equals(type)) {
            // 约会创建人是当前人，则查看所有参加约会的用户信息
            if (datingInfoVo.getCreator() != null && userId != null && datingInfoVo.getCreator().longValue() == userId) {
                DatingRegistrationInfoVo datingRegistrationInfoVo = new DatingRegistrationInfoVo();
                datingRegistrationInfoVo.setDatingId(datingInfoVo.getId());
                List<DatingRegistrationInfoVo> list = datingRegistrationInfoMapper.getList(datingRegistrationInfoVo);
                if (list != null && !list.isEmpty()) {
                    list.forEach(datingRegistrationInfoVo1 -> {
                        if (datingRegistrationInfoVo1.getUserInfoVo() != null && datingRegistrationInfoVo1.getUserInfoVo().getAvatar() != null) {
                            try {
                                FileInfoVo avatar = fileInfoService.queryFileInfo(datingRegistrationInfoVo1.getUserInfoVo().getAvatar());
                                datingRegistrationInfoVo1.getUserInfoVo().setPersonAvatar(avatar);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                }
                datingInfoVo.setDatingRegistrationInfoVos(list);
            }
        }
        return datingInfoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DatingInfoVo addDatingInfo(DatingInfoVo datingInfoVo) throws Exception {
        SecurityUser loginUser = UserUtils.getLoginUser();
        if (loginUser == null) {
            throw new SystemException(ResultEnum.USER_NO_LOGIN);
        }
        UserActivityInfoVo joinEvent = userActivityInfoService.queryUserActivityInfoByUser(loginUser.getId());
        if (joinEvent == null) {
            throw new SystemException(ResultEnum.USER_NOT_PROFILE_COMPLETE.getCode(), "请完善个人信息");
        }
//        UserProfileInfoVo userProfileInfoVo = userProfileInfoService.queryUserProfileInfoByUserId(loginUser.getId());
//        if (userProfileInfoVo == null) {
//            throw new SystemException(ResultEnum.USER_NOT_PROFILE_COMPLETE);
//        }
        UserBalanceInfoVo userBalanceInfoVo = userBalanceInfoService.queryUserBalanceInfoByUserId(loginUser.getId());
        DefaultAmountConfigVo defaultAmountConfigVo = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.CREATE_DATING.getCode());
        BigDecimal paymentAmount;
        // 如果报名金额不为空则使用报名金额，否则查看默认配置表中是否有值，最后查询配置表中配置金额
        if (defaultAmountConfigVo != null) {
            paymentAmount = defaultAmountConfigVo.getAmount();
        } else {
            paymentAmount = defaultAmountConfig.getDating();
        }
        if (datingInfoVo.getTopFlag() != null && datingInfoVo.getTopFlag()) {
            DefaultAmountConfigVo topVo = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.TOP_DATING.getCode());
            paymentAmount = paymentAmount.add(topVo.getAmount());
        }
        if (userBalanceInfoVo == null || userBalanceInfoVo.getBalance().compareTo(paymentAmount) < 0) {
            throw new SystemException(ResultEnum.USER_NO_ENOUGH_BALANCE);
        }
        DatingInfo datingInfo = new DatingInfo();
        BeanUtils.copyProperties(datingInfoVo, datingInfo);
        datingInfo.setCreator(datingInfoVo.getUserId() != null ? datingInfoVo.getUserId() : loginUser.getId());
        datingInfo.setOperator(datingInfoVo.getUserId() != null ? datingInfoVo.getUserId() : loginUser.getId());
        log.info("======================================================");
        log.info("约会数据：{}", JSONObject.toJSONString(datingInfoVo));
        log.info("用户数据:{}", JSONObject.toJSONString(loginUser));
        log.info("请求参数：{}",JSONObject.toJSONString(datingInfo));
        datingInfoMapper.insert(datingInfo);
        UserBalanceInfoAddVo userBalanceInfoAddVo = new UserBalanceInfoAddVo();
        userBalanceInfoAddVo.setUserId(loginUser.getId());
        userBalanceInfoAddVo.setAmount(paymentAmount);
        userBalanceInfoService.reduceAmount(userBalanceInfoAddVo, datingInfo.getId(), TransactionType.START_DATING.getCode(), "发起约会");
        DatingInfoVo res = new DatingInfoVo();
        BeanUtils.copyProperties(datingInfo, res);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DatingInfoVo addDatingInfoBack(DatingInfoVo datingInfoVo) throws Exception {
        SecurityUser loginUser = UserUtils.getLoginUser();
        log.info("添加约会数据：{},当前用户：{}", JSONObject.toJSONString(datingInfoVo), JSONObject.toJSONString(loginUser));
        DatingInfo datingInfo = new DatingInfo();
        BeanUtils.copyProperties(datingInfoVo, datingInfo);
        if (datingInfoVo.getUserId() != null) {
            datingInfo.setCreator(datingInfoVo.getUserId() );
            datingInfo.setOperator(datingInfoVo.getUserId());
        }
        datingInfoMapper.insert(datingInfo);
        DatingInfoVo res = new DatingInfoVo();
        BeanUtils.copyProperties(datingInfo, res);
        return res;
    }

    @Override
    public DatingInfoVo updateDatingInfo(DatingInfoVo datingInfoVo) {
        DatingInfo datingInfo = new DatingInfo();
        BeanUtils.copyProperties(datingInfoVo, datingInfo);
        datingInfo.setOperator(datingInfoVo.getUserId());
        datingInfoMapper.updateById(datingInfo);
        return datingInfoVo;
    }

    @Override
    public Boolean deleteDatingInfo(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return true;
        }
        List<String> idArr = Arrays.asList(ids.split(","));
        datingInfoMapper.deleteBatchIds(idArr);
        return true;
    }
}
